
var api = new TwitterApi(WEB_ROOT + 'twitter/api/');	//twitterのラッパーAPI
var gUser = null;	//ログインユーザー
var gId = null;		//ログインユーザーID
var timeline = new Timeline('mytimeline', 'tweet');	//ホーム
var replies = new Timeline('myreplies', 'reply');	//リプライ
var favorites = new Timeline('myfavorites', 'favorite');	//お気に入り
var univDatas = new Timeline('univdatas','univ');
var followers = null;								//フォロワーページ
var friends = null;									//フォローページ
var twiMsg = new TwiMsg('twi-msg');					//汎用的なメッセージ
var gParam = null;
var bChangedPage = false;
var gAccountUrl = null

//うまく排他制御できていないのでとりあえず
var t = setInterval(function(){bChangedPage = false;}, 3000);
    
function initializeReplies(max_id){
	var data = {count:20,include_rts:1};
	if(max_id != null){
		data['max_id'] = max_id;
	}
	$.mobile.showPageLoadingMsg();
	api.getMentions(data,function(data){
		//console.log(data);
		$.mobile.hidePageLoadingMsg();
		var last, count = 0;;
		if(replies.timelineIds.length != 0){
			last = replies.timelineIds[replies.timelineIds.length - 1];
		}
		
		for(index in data){
			tweet = data[index];
			//max_idを指定した時、同じIDがとれてくるのでそれを回避
			if(last == null || last != tweet.id){
				count++;
				replies.append(tweet);
			}
		}
		
		$("div#reply div.tweet_unit").mouseover(function(){
			$(this).css('background-color','#CCFFCC');
		});
		
		$("div#reply div.tweet_unit").mouseout(function(){
			$(this).css('background-color','#FFFFFF');				
			if($(this).attr('class') == "tweet_unit tweet_unit_myself"){
				$(this).css('background-color','#FFDDEC');								
			}
		});
		
		//アカウントページのイベント
		$("div#reply .tweet_unit img").click(accountShowEvent);
		
		//個々のツイートページのイベント
		$("div#reply div.tweet_unit .tweet").click(tweetShowEvent);
		
		if(count > 0){
			//次を見る奴
			replies.appendNextTweet(); //次を見る
			$('#myreplies div:last').click(function(){
				$(this).remove();
				var max_id = replies.timelineIds[replies.timelineIds.length - 1];
				initializeReplies(max_id);
			});
		}
	});
}

function initializeFavorites(page){
	
	data = {id:gUser.User.id};
	var pageCount = 1;
	if(page != null){
		data['page'] = page;
		pageCount = page;
	}
	// お気に入りとってくる
	api.getFavorites(data,function(data){
		$.mobile.hidePageLoadingMsg();
		//p(data);
		var last,count=0;
		
		if(favorites.timelineIds.length != 0){
			last = favorites.timelineIds[timeline.timelineIds.length - 1];
		}		
		
		for(index in data){
			tweet = data[index];
			//max_idを指定した時、同じIDがとれてくるのでそれを回避
			if(last == null || last != tweet.id){
				count++;
				favorites.append(tweet);
			}
		}
				
		//アカウントページのイベント
		$("#myfavorites div.tweet_unit img").click(accountShowEvent);
		
		//個々のツイートページのイベント
		$("#myfavorites div.tweet_unit .tweet").click(tweetShowEvent);
		
		$("#myfavorites div.tweet_unit").mouseover(function(){
			$(this).css('background-color','#CCFFCC');
		});
		
		$("#myfavorites div.tweet_unit").mouseout(function(){
			$(this).css('background-color','#FFFFFF');
		});
		/*
		$("#account-page").click(function(){
			initializeAccount();
		});
		*/
		//お気に入り、リツイートイベント
		$("#myfavorites div.tweet_unit a.fav").click(favEvent);
		$("#myfavorites div.tweet_unit a.unfav").click(unfavEvent);
		$("#myfavorites div.tweet_unit a.rt").click(retweetEvent);
		$("#myfavorites div.tweet_unit a.unrt").click(unretweetEvent);
		
		if(count > 0){
			//次を見る奴
			favorites.appendNextTweet(); //次を見る
			$('#myfavorites div:last').click(function(){
				$.mobile.showPageLoadingMsg();
				$(this).remove();
				pageCount++;
				initializeFavorites(pageCount);
			});
		}		
	});
	
}


function initializeHomeTimeline(max_id){
	var data = {count:20,include_rts:1};
	if(max_id != null){
		data['max_id'] = max_id;
	}
	$.mobile.showPageLoadingMsg();
	api.getHomeTimeline(data,function(data){
		//console.log(data);
		$.mobile.hidePageLoadingMsg();
		var last, count = 0;
		if(timeline.timelineIds.length != 0){
			last = timeline.timelineIds[timeline.timelineIds.length - 1];
		}
		for(index in data){
			tweet = data[index];
			//max_idを指定した時、同じIDがとれてくるのでそれを回避
			if(last == null || last != tweet.id){
				count++;
				timeline.append(tweet);
			}
		}
		//アカウントページのイベント
		$("div#tweet div.tweet_unit img").click(accountShowEvent);
		
		//個々のツイートページのイベント
		$("div#tweet div.tweet_unit .tweet").click(tweetShowEvent);

		$("div#tweet div.tweet_unit").mouseover(function(){
			$(this).css('background-color','#CCFFCC');
		});
		
		$("div#tweet div.tweet_unit").mouseout(function(){
			if($(this).attr('class') == "tweet_unit tweet_unit_myself"){
				$(this).css('background-color','#FFDDEC');								
			}
			else if($(this).attr('class') == "tweet_unit tweet_unit_myreply"){
				$(this).css('background-color','#FCFF7C');												
			}
			else if($(this).attr('class') == "tweet_unit"){
				$(this).css('background-color','#FFFFFF');				
			}
		});
/*
		$("div#tweet div.tweet_unit_myself").mouseout(function(){
			$(this).css('background-color','#FFDDEC');
		});
*/	
		//お気に入り、リツイートイベント
		/*
		$("div.tweet_unit a.fav").click(favEvent);
		$("div.tweet_unit a.unfav").click(unfavEvent);
		$("div.tweet_unit a.rt").click(retweetEvent);
		$("div.tweet_unit a.unrt").click(unretweetEvent);
		*/
		if(count > 0){
			//次を見る奴
			timeline.appendNextTweet(); //次を見る
			$('#mytimeline div:last').click(function(){
				$(this).remove();
				var max_id = timeline.timelineIds[timeline.timelineIds.length - 1];
				initializeHomeTimeline(max_id);
			});
		}
	});
}

function initializeAccount(userId,screen_name){
	$('.account-page-navi').click(function(){
		initializeMyAccount();
	});
	$('#map_edit_for_me').css('display','none');
	$('#logout_link').css('display','none');
	$('#account').empty();
	$('#account_tweet').empty();
	$('#three_button').hide();
	$('#three_tweet').empty();
	var tweets_link = null;
		
	var params = {};
	if(userId != null){
		params = {user_id :userId };
	}else if(screen_name != null){
		params = {screen_name:screen_name};
	}
		
	if(userId != null || screen_name != null){
		api.showUser(params,function(data){
			//console.log(data);
			//$('#account').empty();
			//$('#three_button').empty();
			//$('#account_tweet').empty();
			tweets_link = WEB_ROOT + 'users/tweets?user_id=' + data.id;
			var followers_link = WEB_ROOT + 'users/followers?user_id=' + data.id;
			var friends_link = WEB_ROOT + 'users/friends?user_id=' + data.id;
			var list = '';
			var inner_three_button = '';
			var inner_account_tweet = '';
			list += '<div class="account">';
			list += '<div class="profile">';
			list += '<div class="img"><a href="'+data.profile_image_url+'"><img src="'+data.profile_image_url+'" alt="test" class="ui-li-icon"></a></div>';
			list += '<div class="right_area">';
			list += '<div class="name">' + data.name + '</div>';
			list += '<div class="screen_name">' + data.screen_name + '</div>';
			list += '</div>'; // right_area
			if(data.description != null){
				list += '<div class="description">' + data.description + '</div>';
			}else{
				list += '<div class="description">' + "" + '</div>';
			}	
			list += '</div>'; // profile
			list += '</div>'; // account
			inner_three_button += '<div data-role="controlgroup" data-type="horizontal">';
			inner_three_button += '<a href="' + tweets_link + '" data-role="button" data-rel="dialog">Tweet:' + data.statuses_count + '</a>';
			inner_three_button += '<a href="' + friends_link + '" data-role="button" data-rel="dialog">Follow:' + data.friends_count + '</a>';
			inner_three_button += '<a href="' + followers_link + '" data-role="button" data-rel="dialog">Follower:' + data.followers_count + '</a>';
			inner_three_button += '</div>';
			inner_account_tweet += '<div class="to_account_tweet">';
			inner_account_tweet += '<div class="to_text">' + data.name + 'さんへツイート</div>';
			inner_account_tweet += '<input type="text" value="@' + data.screen_name + ' "/>';
			inner_account_tweet += '</div>'; // to_account_tweet
			//$('#three_button').show();
			$('.account_tweet_link').attr('href',tweets_link);
			$('.account_follow_link').attr('href',friends_link);
			$('.account_follower_link').attr('href',followers_link);
			$('.account_tweet_link').html('Tweet:' + data.statuses_count);
			$('.account_follow_link').html('Follow:' + data.friends_count);
			$('.account_follower_link').html('Follower:' + data.followers_count);
			$('#account').append(list);
			$('#three_button').show();
			$('#account_tweet').append(inner_account_tweet);
		});
	} else {
		initializeMyAccount();
	}
}

function initializeMyAccount(){
	$('#map_edit_for_me').css('display','block');
	$('#logout_link').css('display','block');
	$('#reply_link').css('display','none');
	api.showUser({user_id:gId},function(data){
		//console.log(data);
		$('#account').empty();
		//$('#three_button').empty();
		$('#account_tweet').empty();
		var tweets_link = WEB_ROOT + 'users/tweets?user_id=' + data.id;
		var followers_link = WEB_ROOT + 'users/followers?user_id=' + data.id;
		var friends_link = WEB_ROOT + 'users/friends?user_id=' + data.id;
		var list = '';
		var inner_three_button = '';
		var inner_account_tweet = '';
		list += '<div class="account">';
		list += '<div class="profile">';
		list += '<div class="img"><a href="'+data.profile_image_url+'"><img src="'+data.profile_image_url+'" alt="test" class="ui-li-icon"></a></div>';
		list += '<div class="right_area">';
		list += '<div class="name">' + data.name + '</div>';
		list += '<div class="screen_name">' + data.screen_name + '</div>';
		list += '</div>'; // right_area
		if(data.description != null){
			list += '<div class="description">' + data.description + '</div>';
		}else{
			list += '<div class="description">' + "" + '</div>';
		}	
		list += '</div>'; // profile
		//list += '<div class="map_link"><a data-role="button" href="">現在地の周辺ツイートを見る</a></div>';
		//list += '<div class="edit_link"><a data-role="button" href="">アカウント情報設定</a></div>';
		list += '</div>'; // account
		inner_three_button += '<div data-role="controlgroup" data-type="horizontal">';
		inner_three_button += '<a href="' + tweets_link + '" data-role="button" data-rel="dialog">Tweet:' + data.statuses_count + '</a>';
		inner_three_button += '<a href="' + friends_link + '" data-role="button" data-rel="dialog">Follow:' + data.friends_count + '</a>';
		inner_three_button += '<a href="' + followers_link + '" data-role="button" data-rel="dialog">Follower:' + data.followers_count + '</a>';
		inner_three_button += '</div>';
		$('.account_tweet_link').attr('href',tweets_link);
		$('.account_follow_link').attr('href',friends_link);
		$('.account_follower_link').attr('href',followers_link);
		$('.account_tweet_link').html('Tweet:' + data.statuses_count);
		$('.account_follow_link').html('Follow:' + data.friends_count);
		$('.account_follower_link').html('Follower:' + data.followers_count);
		$('#account').append(list);
		$('#three_button').show();
		$('#account_tweet').append(inner_account_tweet);
		
		
		
		// 周辺地図表示がクリックされたときの地図表示
		$('#display_map_link').click(function(){
			requestPosition(initializeMap);
		});
	});
}

function initializeTweet(timelineId){
	var latlng = null;
	if(timelineId != null){
		api.setErrorCallback(function(data){
			console.log(data);
		});
		api.showStatuses(timelineId,{},function(data){
			initializeStatusPage(data);
		});
		
		// 周辺地図表示がクリックされたときの地図表示
		$('#display_map_link_from_status').click(function(){
			if(latlng != null){
				initializeMapFromAddress(latlng);
			}
		});
	}
}
/*
function insertUserName(name){
	var insertText = '@' + name;
	$('#reply_tweet').html(insertText);
}

function setReplyUser(id){
	console.log(id);
}
*/

function initializeUnivDatas(statusId){
	var status_id = null;
	if(statusId != null && statusId != ''){
		status_id = statusId;
	}
	//大学に登録していない場合
	if(gUser.Campus.school_id == null){
		return ;
	}
	var schoolId = (gUser.Campus.school_id) ? gUser.Campus.school_id : null;
	console.log(schoolId);
	if(schoolId != null){
		getStatusesBySchoolId(function(data){
			//順番になっていないのでソート
			for(index in data){
				if(index < data.length - 1){
					index2 = index + 1;
				}
				for(index2 in data){
					if(data[index].Status.id > data[index2].Status.id){
						var tmp = data[index];
						data[index] = data[index2];
						data[index2] = tmp;
					}
				}
			}
			$.mobile.hidePageLoadingMsg();
			var last, count = 0;
			if(univDatas.timelineIds.length != 0){
				last = univDatas.timelineIds[univDatas.timelineIds.length - 1];
			}
			for(index in data){
				tweet = data[index];
				//max_idを指定した時、同じIDがとれてくるのでそれを回避
				if(last == null || last != tweet.Status.id){
					count++;
					univDatas.appendForUniv(tweet);
				}
			}
			//アカウントページのイベント
			$("div.tweet_unit img").click(accountShowEvent);
			
			//個々のツイートページのイベント
			$("div.tweet_unit .tweet").click(tweetShowEvent);
			
			$("div.tweet_unit").mouseover(function(){
				$(this).css('background-color','#CCFFCC');
			});
			
			$("div.tweet_unit").mouseout(function(){
				$(this).css('background-color','#FFFFFF');
			});
			
			
			//お気に入り、リツイートイベント
			$("div.tweet_unit a.fav").click(favEvent);
			$("div.tweet_unit a.unfav").click(unfavEvent);
			$("div.tweet_unit a.rt").click(retweetEvent);
			$("div.tweet_unit a.unrt").click(unretweetEvent);
			if(count > 0){
				//次を見る奴
				univDatas.appendNextTweet(); //次を見る
				$('#univdatas div:last').click(function(){
					$(this).remove();
					$.mobile.showPageLoadingMsg();
					//var next_status_id = univDatas.timelineIds[univDatas.timelineIds.length - 1];
					initializeUnivDatas(univDatas.minId);
				});
			}
		
			
		},function(data){
			
		},	schoolId,status_id,null);
	}
}

var initializeUnivDataSuccess = function(data){
	console.log(data);
}

var initializeUnivDataError = function(data){
	//alert(data);
}

function updateTweets(timelineObj, data){
	var tweet = null;
	data.reverse();	//反対に並び替える
	for(index in data){
		tweet = data[index];
		if( data[index].retweeted_status != null && 
		    data[index].retweeted_status  != undefined){
			tweet = data[index].retweeted_status;
		}
		if(!timelineObj.isContain(tweet.id_str)){
			timelineObj.prepend(tweet);
		}
	}
	/*
	//お気に入り、リツイートイベント
	$("div.tweet_unit a.fav").click(favEvent);
	$("div.tweet_unit a.unfav").click(unfavEvent);
	$("div.tweet_unit a.rt").click(retweetEvent);
	$("div.tweet_unit a.unrt").click(unretweetEvent);
	*/
	//アカウントページのイベント
	$("div#reply div.tweet_unit img").click(accountShowEvent);
	$("div#tweet div.tweet_unit img").click(accountShowEvent);
	
	//個々のツイートページのイベント
	$("div#reply div.tweet_unit .tweet").click(tweetShowEvent);
	$("div#tweet div.tweet_unit .tweet").click(tweetShowEvent);
	
	$("div.tweet_unit").mouseover(function(){
		$(this).css('background-color','#CCFFCC');
	});
			
	$("div.tweet_unit").mouseout(function(){
		$(this).css('background-color','#FFFFFF');				
		if($(this).attr('class') == "tweet_unit tweet_unit_myself"){
			$(this).css('background-color','#FFDDEC');								
		}
	});
}

function initializeUI(){
	initializeUser();
}

function initializeUser(){
	getLoginedUser(function(data){
		gUser = data;
		//p(data);
		gId = gUser.User.id;
		gAccountUrl = $('.account-page-navi').attr('href');
		api.getRetweetedByMe({count:100},function(data){
			gUser.rtIds = {};
			//自分のリツイートした情報を残しておく..必要なんです
			for(i in data){
				try{
					gUser.rtIds[data[i].retweeted_status.id_str] = data[i].id_str;
				}catch(e){
					//console.log(data[i]);
				}
			}
			initializeHomeTimeline();
			initializeReplies();
			initializeFavorites();
			initializeUnivDatas();
			initSelectObject();//ここでもう一度読んでイベント付加
			$('.account-page-navi').click(function(){
				initializeMyAccount();
			});
			requestPosition(geoCallback);

			// リスト取得
			/*
			api.getAllLists({user_id:gUser.User.id},function(listData){
				var data = listData;
				$.ajax({
					url : WEB_ROOT + "js/ui/header.php",//ヘッダーの読み込み
					success : function(html){
						//p(html);
						for(index in data){
							var listpage = '';
							listpage += '<div data-role="page" id="list-' + data[index].name + '-page" list_id="'+ data[index].id +'" slug="' + data[index].slug +'">';
							listpage += html;
							//listpage += '<?php echo $this->element("header_twitter"); ?>';
							listpage += '<div data-role="content">';	
							listpage += '<div id="list-' + data[index].name +'"></div>';		
							listpage += '</div>';	
							listpage += '</div>';
							$("div#favorite-page").after(listpage);
						}	
						for(index in data){
							$("select.navi-select").append('<option value="list-'+ data[index].name +'-page">'+ data[index].name +'</option>');
						}
						//headerの処理
						
					}
				});
			});*/

		});
	})
}

/*
function initializeAccountButton(){
	console.log(gId);
	$('#account-page').attr('href',gAccountUrl + '?user_id=' + gId);
	$('#account-page').click(function(){
		$('#account').empty();
		$('#account_tweet').empty();
		$('#three_button').hide();
		$('#three_tweet').empty();
	});
}
*/

$( document ).bind( "pagebeforeshow", function( event, data ){
	var url  = gParam == null ? event.delegateTarget.URL : gParam;
	url = url.replace(/#[a-zA-Z\-_]+/,"");
	var url = $.mobile.path.parseUrl(url);	
	var obj = $.mobile.path.parseUrl(gParam == null ? event.delegateTarget.URL : gParam);	
	var page = getPage(obj.hash);
	var params = makearray(url.search);
	page = page == ""  ? event.currentTarget.location.hash : page;
	//console.log(event.currentTarget.location);
	//console.log(event.delegateTarget.location);
	//console.log(gParam);
	
	// ページにより分岐
	switch(page){
		case "#account-page":
			if(params['user_id'] && gParam != null){
				initializeAccount(params['user_id'],null);
				$('#map_edit_for_me').css('display','none');
			}
			else if(params['screen_name'] && gParam != null){
				initializeAccount(null,params['screen_name']);
				$('#map_edit_for_me').css('display','none');				
			}
			gParam = null;
			bChangedPage = false;//戻す
			break;
		case "#status-page":
			initializeTweet(params['timeline_id']);
			gParam = null;
			bChangedPage = false;//戻す
			break;
	}
	ListEvent(page);	//リストのイベント
	bChangedPage = false;//戻す
});

$( document ).bind( "pageload", function( event, data ){
	
	var obj = $.mobile.path.parseUrl(data.absUrl);
	var params = makearray(obj.search);
	//params['count'] = 50;
	params['cursor'] = "-1";	
	var action = getAction(obj);
	switch(action){
		case 'users/tweets':
			initializeTweetsDialog(params);
			break;
		case 'users/followers':
			followers = new Userslist("myfollowers", "followers");		
			initializeFollowers(params);
			break;
		case 'users/friends':
			friends = new Userslist("myfriends", "friends");
			initializeFriends(params);
			break;
		case 'statuses/add':
		case 'statuses/reply':
			//var status = timeline.get(params['status_id']);
			//送信のメッセージバインド
			//firefox対応
			$("form#StatusAddForm").submit(function(){
				var inputs = $("form#StatusAddForm :input");
				var params = {};
				inputs.each(function(){
					try{
						var name = $(this).attr("name");
						if(name != undefined && typeof name == "string" && name != null){
							if(name.indexOf('data[Status]') != -1){
								params[name] = $(this).val();
							}
						}
						//最後はsubmitなのでここで送信
						if($(this).attr('type') == 'submit'){
							//console.log(params);
							$.mobile.showPageLoadingMsg();
							addStatus(
								function(data){
									$.mobile.hidePageLoadingMsg("ss");
									twiMsg.set(data.msg);　//表示するメッセージのセット
									twiMsg.show();
									$('.ui-dialog').dialog('close'); 
								},
								null,
								params
							);
						}
					}catch(e) {
						//console.log(e);
					}
				});
				return false;
			});
			break;
	}
});



$(document).bind("mobileinit", function(){
	$.mobile.selectmenu.prototype.options.nativeMenu = false;
	//$('select.navi-select').selectmenu({ corners: "false",nativeMenu:"false",theme:"a"});
	initializeUI();
		
	//update-btn
	$('.update-btn').click(updateEvent);

});
